<?
/**
 * 	The general engine functions.
 *
 *  These functions are always accessible and are not class bound.
 *
 *	@copyright	2010 - oneDot only<br>
 *  You can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.<br>
 *  The content is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.  see the GNU General Public License for more details.
 *
 *	@author		Koen Betsens <we@onedotonly.be>
 *  @package 	Global
 */


/**
 * Retreives the general settings
 *
 * If the setting row isn't cashed by default, it will be after the first request (no duplicate DB requests).
 * Some processed variables can be generated:
 *
 * <h2>json:</h2>A key starting with "json:" will return the value as a json parsed object.
 * <h2>style:</h2>A key starting with "style:" will return the style related value, i.e. "style:color" could be "style.beta.color".
 * <h2>type.path</h2>Deprecated? More research needed.
 *
 * @param 	string 	$what		setting key
 * @param 	string 	$value		secondary parameter
 * @return	mixed	usually a string
 */
function engine_get($what, $value=0){
	global $DB;
	
	switch($what){
		case "xmlns" :
			return "xml:lang='".LANG."' lang='".LANG."'";
			break;
			
		case "type.path" :
			if( !$result = $_SESSION['map']['type.path.'.$value]) { 
				$meta = $DB->parse_json($value, "types", "meta");
				$result = $_SESSION['map']['type.path.'.$value] = page_get("crumb:name", $meta->pageid);//($meta->pageid)? $DB->short("name","pages","ID=".$meta->pageid) : 0;
			}
			return $result;
			break;
		
		case (substr($what,0,5) == "json:"):
			$out = engine_get(array_pop(explode(":", $what)));
			return json_decode($out);
			break;
		
		case (substr($what,0,6) == "style:"):
			$what = "style.".engine_get( 'theme' ).".".array_pop( explode( ":", $what ));

		default: 
			if( !$_SESSION['init'][ $what ] )
			 $_SESSION['init'][ $what ] = $DB->query_direct ( "select value from settings where `key`='$what' && active" );
			return $_SESSION['init'][ $what ];
	}
}

/**
 * Retreives the requested file
 *
 * If the setting row isn't cashed by default, it will be after the first request (no duplicate DB requests).
 * Some processed variables can be generated:
 *
 * <h2>json:</h2>A key starting with "json:" will return the value as a json parsed object.
 * <h2>style:</h2>A key starting with "style:" will return the style related value, i.e. "style:color" could be "style.beta.color".
 * <h2>type.path</h2>Deprecated? More research needed.
 *
 * @param 	string 	$what		directory option (usually "ext" for external)
 * @param 	string 	$relative_path		path relative from start directory to file 
 * @param	bool	$once		require_once, defaults true
 * @return	mixed	usually a string
 */
function engine_require( $what, $relative_path, $once = true ){
	
	if( file_exists( $path = ROOT . "engine/$what/$relative_path" ))
		return $once? require_once( $path ) : require( $path );
}

/**
 * Merge 2 or more objects to 1 (ascending)
 * 
 * Does for objects what arra_merge() does for arrays. 
 *
 * @param 	object|array 	$obj0		the to be merged object or array
 * @param 	object|array 	$obj1		the merging object or array
 * @param 	object|array 	$obj2		any additional merging object or array.
 * @return	object	the merged object
 */
function object_merge() {
	
	$merged = array();
	
	if( $objs = func_get_args())
		foreach( $objs as $obj )
			$merged = array_merge( $merged, ( array ) $obj );
	
	return ( object ) $merged;
}

/**
 * Searches the Translate extention 
 *
 * If a translated alternative for the value exists in the Translate extention, it will be returned, otherwise the value itself is returned.
 *
 * @param 	string 	$key		the to be Translated value
 * @return	string	the Tranlsation, or the value itself (incase false).
 */
function translate( $key ) {
	
	$dictionary = (array) $_SESSION[ ENGINE::session_init ]['dictionary'];
	return (( $string = $dictionary[ $key ]->{LANG}) ? $string : $key );
}



/**
 * Limit string ( with additional tail string )
 *
 * returns a substring, relative to given length.
 * In case given first value is an integer, this integer will be considered a textid
 *
 * @param 	mixed 	$string_or_id		the to be limited string; or integer, as textid "long" text identifier.
 * @param 	int 	$length		the character count, defaults to 32
 * @param 	int 	$tail		the ending string, defaults to "..."
 * @return	string	in short: substr( $string, $length ) + $tail
 */
function strlimit( $string_or_id, $length = 32, $tail = "...") {
	global $Engine;
	if( is_int( $string_or_id )) $string_or_id = $Engine->text->get( $string_or_id, "long" );
	
	$string = html_entity_decode( $string_or_id );
	if(strlen( $string )> $length ) $length -= strlen( $tail ); else $tail='';
	return htmlentities( substr( $string, 0, $length )) . $tail;
}

/**
 * Camelize string
 *
 * returns a camelized string, replacing character trailing dot as upper-case.
 * Includes first character capitalized.
 *
 * @param 	string 	$string		the to be camelized
 * @return	string	the edited string, starting with uppercase character.
 */
function camelize( $string ) {
	foreach ( explode( ".", $string ) as $part ) $return[] = ucfirst( $part ); 
	return implode( "", $return);
}

/**
 * Paramise string
 *
 * Returns a processed group of strings and key values.
 *
 * @deprecated 	Not usefull enough to be a global function...
 * @todo	Search & Destroy
 */
function paramise( $attr = false, $string = 1 ) {
		
	if( $attr )
		foreach( $attr as $key => $value ) $attr[ $key ] = "$key = '$value'";
		
	return ( $attr )? (( $string )? implode( " ", $attr ) : $attr ) : "";
}


/**
 * File search
 *
 * checks if given file exists.
 * Returns path to file incase a match is found in the specified $pah or one of iets children.
 *
 * @param 	string 	$path		system start path for file search
 * @param	string	$file		file name
 * @return	string	Searches the 'foo' directory and its children for the existence of bar.txt and returns the path incase existing.
 */
function IsInSubdir( $path, $file ) {
	$dir = opendir( $path );
	
	while (false !== ( $current = readdir( $dir ))) 
		if( strpos( $current, "." ) !== 0 )
		
			if( $current == $file ) {
				
				closedir( $dir );
				return $path . $file;
	
			} else if( is_dir( $path . $current ) && $result = IsInSubdir( "$path$current/", $file )) {
				
				closedir( $dir );
				return $result;
			}
				
	closedir( $dir );
}

/**
 * Error file
 *
 * Include an error file (defaults to 404), or arror segment.
 * Exits by default
 * 
 * @param	$type		Error type
 * @param	$segment	Error page or segment. Defaults to page
 * @param	$exit		Defaults to exit after call
 */
function error( $type = 404, $segment = false, $exit = true ) {
	
	include ENGINE_CORE . "templates/error.php";
	if( $exit ) die();
}
 


?>